/**
 * 
 */
package com.oolong.account.web;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.oolong.account.exception.UserNotExistException;
import com.oolong.account.model.UserModel;
import com.oolong.account.service.ExtraService;

/**
 * @author beralee
 * 
 */
// 标记它是个SPRING的BEAN，是MVC里的C
@Controller
// 表示这个类就是login.do
@RequestMapping("/login.do")
public class LoginController {
	Logger logger = Logger.getLogger(LoginController.class);
	// 表示需要SPRING自动注入
	@Autowired
	private ExtraService extraService;
	String message = " ";

	// 表示这个方法是处理POST方法的
	@RequestMapping(method = RequestMethod.POST)
	// @RequestParam表示将页面上的元素赋给后面的变量，可直接在类里使用
	public String processSubmit(@RequestParam("username") String username,
			@RequestParam("password") String password, ModelMap model,
			HttpServletResponse response, HttpSession session) {
		UserModel userModel;
		response.setContentType("text/html;charset=UTF-8");
		try {
			userModel = extraService.validate(username, password);
		} catch (UserNotExistException e) {
			message = "用户名或密码错误";
			model.addAttribute("message", message);
			return "loginerror";
		} catch (Exception e) {
			message = "用户登录异常";
			model.addAttribute("message", message);
			return "loginerror";
		}
		session.setAttribute("user", userModel);
		return "redirect:index.do";

	}

	@RequestMapping(method = RequestMethod.GET)
	// @RequestParam表示将页面上的元素赋给后面的变量，可直接在类里使用
	public String process(ModelMap model, HttpServletResponse response) {
		model.addAttribute("message", message);
		response.setContentType("text/html;charset=UTF-8");
		return "login";
	}
}
